#!/bin/bash

# 必须以 root 权限运行
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

# 编译所有程序
echo "### Compiling programs..."
make clean
make
if [ $? -ne 0 ]; then
    echo "Make failed, exiting."
    exit 1
fi
echo "### Compilation successful."

# --- 实验参数 ---
# 为了效果明显，文件大小最好大于你的物理内存，或者至少是数百MB
# 这样可以确保数据需要从磁盘读取，而不是一直命中缓存。
FILE_SIZE_MB=1024 # 1 GB
# 1MB 步长是测试内核 readahead 失效的经典场景
STRIDE_KB=1024 
BENCH_CMD="./benchmark $FILE_SIZE_MB stride $STRIDE_KB"
TARGET_FILE_PATH="$(pwd)/testfile.dat"

# 寻找根分区所在的块设备
# 这个命令比原来的更健壮
DEVICE=$(findmnt -n -o SOURCE /)
echo "### Using block device: $DEVICE"

# 清理系统缓存的函数
clear_caches() {
    echo "### Clearing page cache, dentries and inodes..."
    sync
    echo 3 > /proc/sys/vm/drop_caches
    sleep 1
}

# --- 实验流程 ---

echo -e "\n\n============================================================"
echo "## SCENARIO A: BASELINE (NO PREFETCHING) ##"
echo "============================================================"
clear_caches
# 禁用内核预读
blockdev --setra 0 $DEVICE
echo "### Kernel readahead set to 0."
echo "### Running benchmark for Scenario A..."
# 使用 time 命令简单计时，用 perf stat 获取缺页计数
perf stat -e page-faults --  $BENCH_CMD


echo -e "\n\n============================================================"
echo "## SCENARIO B: KERNEL DEFAULT PREFETCHING ##"
echo "============================================================"
clear_caches
# 恢复内核默认预读 (通常是128KB)
blockdev --setra 256 $DEVICE
echo "### Kernel readahead set to default (128KB)."
echo "### Running benchmark for Scenario B..."
perf stat -e page-faults --  $BENCH_CMD


echo -e "\n\n============================================================"
echo "## SCENARIO C: EBPF ADAPTIVE PREFETCHER ##"
echo "============================================================"
echo "This scenario is interactive. Please follow the steps in two terminals."
echo
echo "--- INSTRUCTIONS ---"
echo "1. In this terminal, we will now run the benchmark. It will print its PID and wait."
echo "2. Open a NEW terminal, navigate to this directory."
echo "3. In the NEW terminal, run the command: sudo ./prefetcher <PID> $TARGET_FILE_PATH"
echo "   (Replace <PID> with the PID shown in this terminal)."
echo "4. After the prefetcher starts, come back to THIS terminal and press Enter to continue the benchmark."
echo "--------------------"
echo

clear_caches
# 禁用内核预读，避免干扰
blockdev --setra 0 $DEVICE
echo "### Kernel readahead set to 0 for our test."
echo "### Running benchmark for Scenario C..."
# benchmark 会打印PID并暂停，等待我们启动 prefetcher
perf stat -e page-faults --  $BENCH_CMD

echo -e "\n### Experiment finished. Restoring readahead to default."
blockdev --setra 256 $DEVICE
rm -f testfile.dat